import axios from 'axios'
import { useAuthStore } from '../stores/auth.store'

// 创建axios实例
const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    const token = authStore.getToken()
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    const authStore = useAuthStore()
    
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，清除用户信息并跳转到登录页
          authStore.clearUser()
          window.location.href = '/login'
          break
        case 403:
          // 权限不足
          console.error('Permission denied')
          break
        case 500:
          console.error('Server error')
          break
        default:
          console.error(`Error: ${error.response.status}`)
      }
    }
    
    return Promise.reject(error)
  }
)

export default http